package com.codeczx.nightmodedemo;

import android.content.pm.ConfigurationInfo;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tvShowMode;
    private Button btnChangeMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState==null){
            // 为每个activity单独设置模式
            getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            recreate();
        }
        setContentView(R.layout.activity_main);
        tvShowMode = (TextView) findViewById(R.id.tv_show_mode);
        btnChangeMode = (Button) findViewById(R.id.btn_change_mode);

        btnChangeMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentNightMode = getResources().getConfiguration().uiMode
                        & Configuration.UI_MODE_NIGHT_MASK;
                switch (currentNightMode) {
                    case Configuration.UI_MODE_NIGHT_NO:
                        getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                        break;
                    case Configuration.UI_MODE_NIGHT_YES:
                        getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                        break;
                }
                recreate();
            }
        });

        showNightMode();
    }

    private void showNightMode(){
        int currentNightMode = getResources().getConfiguration().uiMode
                & Configuration.UI_MODE_NIGHT_MASK;
        String str = null;
        switch (currentNightMode) {
            case Configuration.UI_MODE_NIGHT_NO:
                str = "UI_MODE_NIGHT_NO";
                break;
            case Configuration.UI_MODE_NIGHT_YES:
                str = "UI_MODE_NIGHT_YES";
                break;
            case Configuration.UI_MODE_NIGHT_UNDEFINED:
                str = "UI_MODE_NIGHT_UNDEFINED";
                break;
        }
        tvShowMode.setText(str);
    }
}
